package platform

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonmodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/payment"

	"gitee.com/wangshh_123/cross-pay-go/src/errors"

	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// PhotonPayController 光子支付控制器
type PhotonPayController struct {
	photonPayService *service.PhotonPayService
	client           *photonpay.PhotonPayClient
	hlPayClient      *hlPay.HlPayClient // 添加 HlPay 客户端支持
	db               *gorm.DB
}

// NewPhotonPayController 创建光子支付控制器
func NewPhotonPayController(client *photonpay.PhotonPayClient, hlPayClient *hlPay.HlPayClient) *PhotonPayController {
	return &PhotonPayController{
		photonPayService: service.NewPhotonPayService(client),
		client:           client,
		hlPayClient:      hlPayClient,
		db:               database.DB,
	}
}

// getMatrixAccountFromToken 从token中获取matrixAccount信息
func (c *PhotonPayController) getMatrixAccountFromToken(ctx *gin.Context) (*models.MatrixAccountInfo, error) {
	// 从中间件中获取matrix账户信息
	matrixAccountInfo, exists := ctx.Get("matrix_account_info")
	if !exists {
		return nil, errors.NewAppError(http.StatusUnauthorized, "matrix_account_not_found", nil)
	}

	// 类型断言
	matrixAccount, ok := matrixAccountInfo.(*models.UserMatrixAccount)
	if !ok {
		return nil, errors.NewAppError(http.StatusInternalServerError, "invalid_matrix_account_type", nil)
	}

	return &models.MatrixAccountInfo{
		UserID:            matrixAccount.UserID,
		MatrixAccount:     matrixAccount.MatrixAccount,
		MatrixAccountName: matrixAccount.MatrixAccountName,
	}, nil
}

// PhotonPayUserRoleBalance 用户角色和余额信息
type PhotonPayUserRoleBalance struct {
	RoleID  int64
	UserID  int64
	Balance decimal.Decimal
}

// getUserRoleAndBalance 获取用户角色和余额信息
func (c *PhotonPayController) getUserRoleAndBalance(ctx *gin.Context) (*PhotonPayUserRoleBalance, error) {
	claims, exists := ctx.Get("claims")
	if !exists {
		return nil, errors.NewAppError(http.StatusUnauthorized, "unauthorized", nil)
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		return nil, errors.NewAppError(http.StatusInternalServerError, "invalid_token_claims", nil)
	}

	userID := authClaims.UserID
	roleID := authClaims.RoleID
	var balance decimal.Decimal

	switch roleID {
	case 2: // 普通用户 - 返回0余额
		balance = decimal.Zero
	case 3: // 主账号
		var masterAccount models.MasterAccount
		if err := c.db.Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
			return nil, errors.NewAppError(http.StatusInternalServerError, "get_master_account_failed", err)
		}
		balance = masterAccount.Balance
	case 5: // 子账号
		var subAccount models.SubAccount
		if err := c.db.Where("user_id = ?", userID).First(&subAccount).Error; err != nil {
			return nil, errors.NewAppError(http.StatusInternalServerError, "get_sub_account_failed", err)
		}
		balance = subAccount.Balance
	}

	return &PhotonPayUserRoleBalance{
		RoleID:  roleID,
		UserID:  userID,
		Balance: balance,
	}, nil
}

// checkAndDeductBalance 检查并扣除余额
func (c *PhotonPayController) checkAndDeductBalance(tx *gorm.DB, roleID int64, userID int64, amount float64) error {
	amountDecimal := decimal.NewFromFloat(amount)

	switch roleID {
	case 2: // 普通用户 - 不需要检查余额
		return nil
	case 3: // 主账号
		var masterAccount models.MasterAccount
		if err := tx.Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
			return err
		}
		if masterAccount.Balance.LessThan(amountDecimal) {
			return errors.NewAppError(http.StatusBadRequest, "insufficient_master_balance", nil)
		}
		if err := tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error; err != nil {
			return err
		}
	case 5: // 子账号
		var subAccount models.SubAccount
		if err := tx.Where("user_id = ?", userID).First(&subAccount).Error; err != nil {
			return err
		}
		if subAccount.Balance.LessThan(amountDecimal) {
			return errors.NewAppError(http.StatusBadRequest, "insufficient_sub_balance", nil)
		}
		if err := tx.Model(&models.SubAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error; err != nil {
			return err
		}
	}
	return nil
}

// ==================== 卡片管理相关接口 ====================

// GetCardBin 获取卡BIN信息
func (c *PhotonPayController) GetCardBin(ctx *gin.Context) {
	params := photonmodels.CardBinQueryParams{
		CardFormFactor: ctx.Query("card_form_factor"),
		CardType:       ctx.Query("card_type"),
		CardScheme:     ctx.Query("card_scheme"),
		CardCurrency:   ctx.Query("card_currency"),
	}

	result, err := services.GetCardBin(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_card_bin_failed", err)
		return
	}

	common.Success(ctx, result)
}

// GetSupportedPlatforms 获取支持的平台列表
func (c *PhotonPayController) GetSupportedPlatforms(ctx *gin.Context) {
	platforms := []gin.H{
		{
			"platform":    "photonpay",
			"name":        "光子支付",
			"description": "光子支付平台卡BIN查询",
			"supported_features": []string{
				"card_form_factor_filter",
				"card_type_filter",
				"card_scheme_filter",
				"card_currency_filter",
			},
		},
		{
			"platform":    "hlpay",
			"name":        "HL支付",
			"description": "HL支付平台卡BIN查询",
			"supported_features": []string{
				"basic_bin_query",
			},
		},
	}

	common.Success(ctx, gin.H{
		"platforms": platforms,
		"total":     len(platforms),
	})
}

// GetCardList 获取卡片列表
func (c *PhotonPayController) GetCardList(ctx *gin.Context) {
	// 获取矩阵账户信息
	matrixAccountInfo, err := common.GetMatrixAccountInfo(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", err)
		return
	}

	// 获取用户角色
	claims, exists := ctx.Get("claims")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_token_claims", nil)
		return
	}
	roleID := authClaims.RoleID
	userID := authClaims.UserID

	// 获取分页参数
	page, pageSize := common.GetPaginationParams(ctx)

	// 获取过滤参数
	nickname := ctx.Query("nickname")
	maskCardNo := ctx.Query("cardNo")
	cardType := ctx.Query("cardType")

	// 构建查询参数 - 获取较大数量的数据以便在内存中过滤
	params := photonmodels.CardListQueryParams{
		PageIndex:      1,
		PageSize:       1000, // 获取较大数量的数据
		MatrixAccount:  matrixAccountInfo.MatrixAccount,
		CardBin:        ctx.Query("cardBin"),
		CreatedAtStart: ctx.Query("createdAtStart"),
		CreatedAtEnd:   ctx.Query("createdAtEnd"),
		CardType:       cardType,
		CardFormFactor: ctx.Query("cardFormFactor"),
		CardStatus:     ctx.Query("cardStatus"),
	}

	// 调用服务获取卡片列表
	response, err := services.GetCardList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_card_list_failed", err)
		return
	}

	// 在内存中进行过滤
	filteredCards := make([]photonmodels.CardInfo, 0)
	for i := range response.Data {
		card := &response.Data[i]
		// 只有子账号用户需要过滤自己的卡
		if roleID == 5 {
			var userCard models.UserCard
			if err := c.db.Where("card_id = ? AND user_id = ?", card.CardID, userID).First(&userCard).Error; err != nil {
				continue // 如果查询失败或卡不属于该用户，跳过
			}
		}

		// 检查 nickname 匹配
		if nickname != "" && !strings.Contains(strings.ToLower(card.Nickname), strings.ToLower(nickname)) {
			continue
		}
		// 检查 maskCardNo 匹配
		if maskCardNo != "" && !strings.Contains(card.MaskCardNo, maskCardNo) {
			continue
		}

		// 如果是共享卡，设置交易限额
		if cardType == "share" {
			var userCard models.UserCard
			if err := c.db.Where("card_id = ?", card.CardID).First(&userCard).Error; err == nil {
				limit := userCard.TotalTransferAmount.InexactFloat64()
				card.TransactionLimit = &limit
			}
		}

		filteredCards = append(filteredCards, *card)
	}

	// 计算分页
	total := int64(len(filteredCards))
	start := (page - 1) * pageSize
	end := start + pageSize
	if start >= total {
		start = total
	}
	if end > total {
		end = total
	}

	// 更新响应数据
	response.Data = filteredCards[start:end]
	response.PageIndex = int64(page)
	response.PageSize = int64(pageSize)
	response.Total = total

	// 构建标准响应格式
	standardResponse := gin.H{
		"code": "200",
		"msg": map[string]string{
			"CN": "操作成功",
			"EN": "Operation successful",
			"VN": "Thao tác thành công",
		},
		"data": gin.H{
			"code":      "0000",
			"msg":       "succeed",
			"data":      response.Data,
			"pageIndex": response.PageIndex,
			"pageSize":  response.PageSize,
			"total":     response.Total,
		},
	}

	// 返回成功响应
	ctx.JSON(http.StatusOK, standardResponse)
}

// GetCardDetail 获取卡片详情
func (c *PhotonPayController) GetCardDetail(ctx *gin.Context) {
	cardID := ctx.Query("card_id")
	if cardID == "" {
		common.Error(ctx, http.StatusBadRequest, "card_id_required", nil)
		return
	}

	// 从中间件中获取claims
	claims, exists := ctx.Get("claims")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	// 类型断言
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_token_claims", nil)
		return
	}

	// 从claims中获取用户ID
	userID := authClaims.UserID

	// 创建带有用户ID的上下文
	ctxWithUserID := context.WithValue(ctx.Request.Context(), "userID", userID)

	result, err := services.GetCardDetail(ctxWithUserID, c.client, cardID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_card_detail_failed", err)
		return
	}

	// 解析响应数据
	var responseData map[string]interface{}
	if err := json.Unmarshal(result, &responseData); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_response_failed", err)
		return
	}

	// 检查响应状态
	if code, ok := responseData["code"].(string); !ok || (code != "0000" && code != "200") {
		common.Error(ctx, http.StatusInternalServerError, "get_card_detail_failed", fmt.Errorf("API returned error code: %v", code))
		return
	}

	// 开始事务
	tx := c.db.Begin()
	if tx.Error != nil {
		common.Error(ctx, http.StatusInternalServerError, "transaction_start_failed", tx.Error)
		return
	}
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 检查卡是否存在于本地数据库
	var userCard models.UserCard
	if err := tx.Where("card_id = ?", cardID).First(&userCard).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			// 卡不存在，需要创建新记录
			if data, ok := responseData["data"].(map[string]interface{}); ok {
				// 从API响应中获取卡信息
				cardBin := "111111" // 默认值
				if bin, ok := data["cardBin"].(string); ok {
					cardBin = bin
				}

				cardType := "recharge" // 默认值
				if cType, ok := data["cardType"].(string); ok {
					cardType = cType
				}

				nickname := ""
				if nick, ok := data["nickname"].(string); ok {
					nickname = nick
				}

				// 获取卡余额
				var cardBalance float64
				if balance, ok := data["cardBalance"].(float64); ok {
					cardBalance = balance
				} else if balance, ok := data["cardBalance"].(string); ok {
					if parsed, err := strconv.ParseFloat(balance, 64); err == nil {
						cardBalance = parsed
					}
				}

				// 创建新的卡记录
				newUserCard := models.UserCard{
					UserID:              userID,
					CardID:              cardID,
					Platform:            "photonpay",
					CardStatus:          "active",
					CardBin:             cardBin,
					NikeName:            nickname,
					TotalTransferAmount: decimal.NewFromFloat(cardBalance),
					CardType:            cardType,
				}

				if err := tx.Create(&newUserCard).Error; err != nil {
					tx.Rollback()
					log.Printf("Failed to create new card record: %v", err)
					common.Error(ctx, http.StatusInternalServerError, "create_card_record_failed", err)
					return
				}

				log.Printf("Created new card record for card %s with balance %.2f", cardID, cardBalance)
			}
		} else {
			tx.Rollback()
			common.Error(ctx, http.StatusInternalServerError, "database_error", err)
			return
		}
	} else {
		// 卡已存在，检查是否需要更新余额
		if data, ok := responseData["data"].(map[string]interface{}); ok {
			// 获取当前卡余额
			var cardBalance float64
			if balance, ok := data["cardBalance"].(float64); ok {
				cardBalance = balance
			} else if balance, ok := data["cardBalance"].(string); ok {
				if parsed, err := strconv.ParseFloat(balance, 64); err == nil {
					cardBalance = parsed
				}
			}

			// 如果本地记录的TotalTransferAmount为0，但API返回的余额不为0，则更新
			if userCard.TotalTransferAmount.Equal(decimal.Zero) && cardBalance > 0 {
				updates := map[string]interface{}{
					"TotalTransferAmount": decimal.NewFromFloat(cardBalance),
				}

				// 更新卡片信息
				if err := tx.Model(&models.UserCard{}).
					Where("card_id = ?", cardID).
					Updates(updates).Error; err != nil {
					tx.Rollback()
					log.Printf("Failed to update card balance: %v", err)
					common.Error(ctx, http.StatusInternalServerError, "update_card_balance_failed", err)
					return
				}

				log.Printf("Updated card %s balance from 0 to %.2f", cardID, cardBalance)
			}
		}
	}

	// 检查是否有特殊格式的nickname
	if data, ok := responseData["data"].(map[string]interface{}); ok {
		if nickname, ok := data["nickname"].(string); ok && nickname != "" {
			// 尝试解析特殊格式的nickname
			var nicknameData struct {
				TotalRechargeAmount float64 `json:"totalrechargeAmount"`
				Nickname            string  `json:"nickname"`
			}
			if err := json.Unmarshal([]byte(nickname), &nicknameData); err == nil {
				// 先查询当前卡片的TotalTransferAmount
				var currentUserCard models.UserCard
				if err := tx.Where("card_id = ?", cardID).First(&currentUserCard).Error; err == nil {
					// 只有当TotalTransferAmount为0且从未被赋值过时才更新
					updates := map[string]interface{}{
						"nike_name": nicknameData.Nickname,
					}

					// 检查卡片是否是新创建的（通过created_at和updated_at是否相同来判断）
					isNewCard := currentUserCard.CreatedAt.Equal(currentUserCard.UpdatedAt)

					// 更严格的检查条件：只有当TotalTransferAmount为0且是新卡片时才更新
					if currentUserCard.TotalTransferAmount.Equal(decimal.Zero) && isNewCard && nicknameData.TotalRechargeAmount > 0 {
						updates["TotalTransferAmount"] = nicknameData.TotalRechargeAmount

						// 查询用户的矩阵账户信息
						var matrixAccount models.UserMatrixAccount
						if err := tx.Where("user_id = ? AND platform_type = 'photonpay'", userID).First(&matrixAccount).Error; err == nil {
							// 查询主账号信息
							var masterAccount models.MasterAccount
							if err := tx.Where("user_id = ?", userID).First(&masterAccount).Error; err == nil {
								// 添加余额上限检查，防止异常巨大的余额
								if nicknameData.TotalRechargeAmount > 1000000 {
									log.Printf("警告：卡片 %s 的充值金额异常巨大: %.2f，跳过余额更新", cardID, nicknameData.TotalRechargeAmount)
									// 不更新余额，只更新卡片信息
									delete(updates, "TotalTransferAmount")
								} else {
									// 更新主账号余额
									if err := tx.Model(&models.MasterAccount{}).
										Where("user_id = ?", userID).
										Update("balance", gorm.Expr("balance + ?", nicknameData.TotalRechargeAmount)).Error; err != nil {
										tx.Rollback()
										log.Printf("Failed to update master account balance: %v", err)
										return
									}
									log.Printf("成功更新主账号余额，用户ID: %d, 增加金额: %.2f", userID, nicknameData.TotalRechargeAmount)
								}
							}
						}
					} else {
						log.Printf("跳过余额更新：卡片 %s TotalTransferAmount=%.2f, isNewCard=%v, TotalRechargeAmount=%.2f",
							cardID, currentUserCard.TotalTransferAmount, isNewCard, nicknameData.TotalRechargeAmount)
					}

					// 更新数据库中的卡片信息
					if err := tx.Model(&models.UserCard{}).
						Where("card_id = ?", cardID).
						Updates(updates).Error; err != nil {
						tx.Rollback()
						log.Printf("Failed to update card info: %v", err)
						return
					}

					// 如果本地更新成功，调用UpdateCard接口将昵称改回原来的值
					updateBody := map[string]interface{}{
						"cardId":    cardID,
						"requestId": fmt.Sprintf("UPDATE_%d", time.Now().UnixNano()),
						"nickname":  currentUserCard.NikeName, // 使用原来的昵称
					}
					updateBytes, err := json.Marshal(updateBody)
					if err != nil {
						log.Printf("Failed to marshal update request: %v", err)
					} else {
						_, err = services.UpdateCard(ctx.Request.Context(), c.client, updateBytes)
						if err != nil {
							log.Printf("Failed to update card nickname: %v", err)
						}
					}
				}
			}
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		log.Printf("Failed to commit transaction: %v", err)
		common.Error(ctx, http.StatusInternalServerError, "transaction_commit_failed", err)
		return
	}

	common.Success(ctx, result)
}

// OpenCard 开卡
func (c *PhotonPayController) OpenCard(ctx *gin.Context) {
	matrixAccount, err := common.GetMatrixAccountInfo(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "matrix_account_not_found", err)
		return
	}

	// 获取用户角色和余额信息
	userInfo, err := c.getUserRoleAndBalance(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	var req struct {
		AccountId            string `json:"accountId" binding:"omitempty"`
		CardBin              string `json:"cardBin" binding:"required"`
		CardholderId         string `json:"cardholderId" binding:"required"`
		CardCurrency         string `json:"cardCurrency" binding:"required"`
		CardExpirationDate   int    `json:"cardExpirationDate" binding:"required"`
		CardScheme           string `json:"cardScheme" binding:"required"`
		CardType             string `json:"cardType" binding:"required"`
		CardFormFactor       string `json:"cardFormFactor" binding:"required"`
		RechargeAmount       string `json:"rechargeAmount" binding:"omitempty"`
		RequestId            string `json:"requestId" binding:"required"`
		TransactionLimitType string `json:"transactionLimitType" binding:"omitempty"`
		Nickname             string `json:"nickname"`
		CardCount            int    `json:"cardCount,CardCount" binding:"omitempty,min=1,max=10"` // 批量开卡数量，1-10张，支持两种大小写
		TimeoutSeconds       int    `json:"timeoutSeconds" binding:"omitempty,min=5,max=60"`      // 超时时间（秒），5-60秒，默认15秒
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证cardholderId
	if req.CardholderId == "" || req.CardholderId == "undefined" {
		common.Error(ctx, http.StatusBadRequest, "invalid_cardholder_id", fmt.Errorf("cardholderId is required and cannot be 'undefined'"))
		return
	}

	// 设置默认开卡数量为1
	if req.CardCount <= 0 {
		req.CardCount = 1
	}

	// 设置默认超时时间为15秒
	if req.TimeoutSeconds <= 0 {
		req.TimeoutSeconds = 15
	}

	// 检查余额（批量开卡时，总充值金额 = 单张卡充值金额 × 开卡数量）
	if req.RechargeAmount != "" && userInfo.RoleID != 2 {
		rechargeAmount, err := strconv.ParseFloat(req.RechargeAmount, 64)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_recharge_amount", err)
			return
		}

		totalRechargeAmount := rechargeAmount * float64(req.CardCount)
		if userInfo.Balance.LessThan(decimal.NewFromFloat(totalRechargeAmount)) {
			common.Error(ctx, http.StatusBadRequest, "insufficient_balance", nil)
			return
		}
	}

	// 批量开卡结果
	var batchResults []map[string]interface{}
	var successCount int
	var failedCount int
	var totalDeductAmount float64

	// 批量开卡 - 使用独立事务处理每张卡
	for i := 1; i <= req.CardCount; i++ {
		// 生成卡昵称：用户输入名称+[序号]
		cardNikeName := req.Nickname
		if req.CardCount > 1 {
			cardNikeName = fmt.Sprintf("%s[%d]", req.Nickname, i)
		}

		// 生成唯一的requestId
		uniqueRequestId := fmt.Sprintf("%s_%d", req.RequestId, i)

		// 记录调试信息
		log.Printf("Processing card %d/%d: nikeName=%s, requestId=%s", i, req.CardCount, cardNikeName, uniqueRequestId)

		// 为每张卡创建独立的事务
		cardTx := c.db.Begin()
		if cardTx.Error != nil {
			log.Printf("Failed to start transaction for card %d: %v", i, cardTx.Error)
			failedCount++
			batchResults = append(batchResults, map[string]interface{}{
				"card_index": i,
				"status":     "failed",
				"error":      "transaction_start_failed",
				"details":    cardTx.Error.Error(),
			})
			continue
		}

		// 使用defer确保事务回滚
		cardSuccess := false
		defer func() {
			if !cardSuccess {
				cardTx.Rollback()
			}
		}()

		bodyBytes, err := json.Marshal(map[string]interface{}{
			"userId":               userInfo.UserID,
			"matrixAccount":        matrixAccount.MatrixAccount,
			"accountId":            req.AccountId,
			"cardBin":              req.CardBin,
			"cardholderId":         req.CardholderId,
			"cardCurrency":         req.CardCurrency,
			"cardExpirationDate":   req.CardExpirationDate,
			"cardScheme":           req.CardScheme,
			"cardType":             req.CardType,
			"cardFormFactor":       req.CardFormFactor,
			"rechargeAmount":       req.RechargeAmount,
			"requestId":            uniqueRequestId,
			"transactionLimitType": req.TransactionLimitType,
			"nikeName":             cardNikeName,
		})
		if err != nil {
			log.Printf("Failed to marshal request for card %d: %v", i, err)
			failedCount++
			batchResults = append(batchResults, map[string]interface{}{
				"card_index": i,
				"status":     "failed",
				"error":      "request_marshal_failed",
				"details":    err.Error(),
			})
			continue
		}

		// 记录请求体（调试用）
		log.Printf("Request body for card %d: %s", i, string(bodyBytes))

		// 创建带超时的上下文（使用配置的超时时间）
		ctxWithTimeout, cancel := context.WithTimeout(ctx.Request.Context(), time.Duration(req.TimeoutSeconds)*time.Second)
		defer cancel()

		// 添加重试机制
		var result []byte
		var apiErr error
		maxRetries := 2
		for retry := 0; retry <= maxRetries; retry++ {
			if retry > 0 {
				log.Printf("Retrying card %d, attempt %d/%d", i, retry+1, maxRetries+1)
				// 重试前等待一小段时间
				time.Sleep(time.Duration(retry) * 500 * time.Millisecond)
			}

			result, apiErr = services.OpenCard(ctxWithTimeout, c.client, bodyBytes)
			if apiErr == nil {
				break
			}

			// 检查是否是超时错误，如果是则重试
			if ctxWithTimeout.Err() == context.DeadlineExceeded {
				log.Printf("Card %d request timeout on attempt %d (%ds)", i, retry+1, req.TimeoutSeconds)
				if retry == maxRetries {
					failedCount++
					batchResults = append(batchResults, map[string]interface{}{
						"card_index": i,
						"status":     "failed",
						"error":      "request_timeout",
						"timeout":    fmt.Sprintf("%ds", req.TimeoutSeconds),
						"retries":    retry + 1,
					})
					break
				}
				continue
			}

			// 其他错误，记录但不重试
			log.Printf("Failed to open card %d on attempt %d: %v", i, retry+1, apiErr)
			if retry == maxRetries {
				failedCount++
				batchResults = append(batchResults, map[string]interface{}{
					"card_index": i,
					"status":     "failed",
					"error":      apiErr.Error(),
					"retries":    retry + 1,
				})
			}
			break
		}

		if apiErr != nil {
			continue
		}

		// 记录响应（调试用）
		log.Printf("Response for card %d: %s", i, string(result))

		// 解析响应数据
		var responseData map[string]interface{}
		if err := json.Unmarshal(result, &responseData); err != nil {
			log.Printf("Failed to parse response for card %d: %v", i, err)
			failedCount++
			batchResults = append(batchResults, map[string]interface{}{
				"card_index": i,
				"status":     "failed",
				"error":      "parse_response_failed",
				"details":    err.Error(),
			})
			continue
		}

		// 检查开卡是否成功
		if code, ok := responseData["code"].(string); ok && (code == "0000" || code == "200") {
			if data, ok := responseData["data"].(map[string]interface{}); ok {
				if cardID, ok := data["cardId"].(string); ok {
					// 检查卡是否已存在
					var existingCard models.UserCard
					if err := cardTx.Where("card_id = ?", cardID).First(&existingCard).Error; err == nil {
						// 卡已存在，跳过创建
						log.Printf("Card %d already exists: %s", i, cardID)
						successCount++
						batchResults = append(batchResults, map[string]interface{}{
							"card_index": i,
							"status":     "success",
							"card_id":    cardID,
							"nike_name":  cardNikeName,
							"data":       responseData,
							"note":       "card_already_exists",
						})
						cardSuccess = true
						cardTx.Commit()
						continue
					}

					// 创建用户卡记录
					userCard := models.UserCard{
						UserID:              userInfo.UserID,
						CardID:              cardID,
						Platform:            "photonpay",
						CardStatus:          "active",
						CardBin:             req.CardBin,
						NikeName:            cardNikeName,
						TotalTransferAmount: decimal.NewFromInt(0),
						CardType:            req.CardType,
					}
					if err := cardTx.Create(&userCard).Error; err != nil {
						log.Printf("Failed to create user card record for card %d: %v", i, err)
						failedCount++
						batchResults = append(batchResults, map[string]interface{}{
							"card_index": i,
							"status":     "failed",
							"error":      "database_error",
							"details":    err.Error(),
						})
						continue
					}

					// 提交事务
					if err := cardTx.Commit().Error; err != nil {
						log.Printf("Failed to commit transaction for card %d: %v", i, err)
						failedCount++
						batchResults = append(batchResults, map[string]interface{}{
							"card_index": i,
							"status":     "failed",
							"error":      "transaction_commit_failed",
							"details":    err.Error(),
						})
						continue
					}

					successCount++
					cardSuccess = true
					batchResults = append(batchResults, map[string]interface{}{
						"card_index": i,
						"status":     "success",
						"card_id":    cardID,
						"nike_name":  cardNikeName,
						"data":       responseData,
					})

					// 累计成功开卡的充值金额
					if req.RechargeAmount != "" {
						if rechargeAmount, err := strconv.ParseFloat(req.RechargeAmount, 64); err == nil {
							totalDeductAmount += rechargeAmount
						}
					}
				} else {
					failedCount++
					batchResults = append(batchResults, map[string]interface{}{
						"card_index": i,
						"status":     "failed",
						"error":      "card_id_not_found",
						"response":   responseData,
					})
				}
			} else {
				failedCount++
				batchResults = append(batchResults, map[string]interface{}{
					"card_index": i,
					"status":     "failed",
					"error":      "response_data_not_found",
					"response":   responseData,
				})
			}
		} else {
			failedCount++
			// 获取错误信息，处理可能为null的情况
			var errorMsg interface{}
			if msg, exists := responseData["message"]; exists && msg != nil {
				errorMsg = msg
			} else if msg, exists := responseData["msg"]; exists && msg != nil {
				errorMsg = msg
			} else {
				errorMsg = "unknown_error"
			}

			batchResults = append(batchResults, map[string]interface{}{
				"card_index": i,
				"status":     "failed",
				"error":      errorMsg,
				"code":       responseData["code"],
				"response":   responseData,
			})

			// 记录详细错误信息到日志
			log.Printf("Card %d failed with response: %+v", i, responseData)
		}
	}

	// 如果有充值金额且开卡成功，扣除相应余额
	if req.RechargeAmount != "" && successCount > 0 && totalDeductAmount > 0 {
		// 使用独立事务处理余额扣除
		balanceTx := c.db.Begin()
		if balanceTx.Error != nil {
			log.Printf("Failed to start balance deduction transaction: %v", balanceTx.Error)
			// 不影响开卡结果，只记录错误
		} else {
			if err := c.checkAndDeductBalance(balanceTx, userInfo.RoleID, userInfo.UserID, totalDeductAmount); err != nil {
				balanceTx.Rollback()
				log.Printf("Failed to deduct balance: %v", err)
				// 不影响开卡结果，只记录错误
			} else {
				if err := balanceTx.Commit().Error; err != nil {
					log.Printf("Failed to commit balance deduction: %v", err)
				}
			}
		}
	}

	// 返回批量开卡结果
	common.Success(ctx, gin.H{
		"batch_summary": gin.H{
			"total_cards":   req.CardCount,
			"success_count": successCount,
			"failed_count":  failedCount,
			"success_rate":  fmt.Sprintf("%.2f%%", float64(successCount)/float64(req.CardCount)*100),
		},
		"card_results": batchResults,
		"message":      fmt.Sprintf("批量开卡完成：成功 %d 张，失败 %d 张", successCount, failedCount),
	})
}

// FreezeCard 冻结卡片
func (c *PhotonPayController) FreezeCard(ctx *gin.Context) {
	var req struct {
		CardID    string `json:"cardId" binding:"required"`
		Status    string `json:"status" binding:"required,oneof=freeze unfreeze"`
		RequestId string `json:"requestId" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	bodyBytes, err := json.Marshal(map[string]interface{}{
		"cardId":    req.CardID,
		"status":    req.Status,
		"requestId": req.RequestId,
	})
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.FreezeCard(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "freeze_card_failed", err)
		return
	}

	// 解析响应数据
	var responseData map[string]interface{}
	if err := json.Unmarshal(result, &responseData); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_response_failed", err)
		return
	}

	// 检查响应状态
	if code, ok := responseData["code"].(string); !ok || code != "200" {
		msg := "冻结卡片失败"
		if req.Status == "unfreeze" {
			msg = "解冻卡片失败"
		}
		common.Error(ctx, http.StatusInternalServerError, msg, fmt.Errorf("code: %v, msg: %v", code, responseData["msg"]))
		return
	}

	// 开始事务
	tx := c.db.Begin()
	if tx.Error != nil {
		common.Error(ctx, http.StatusInternalServerError, "start_transaction_failed", tx.Error)
		return
	}

	// 获取当前卡片状态
	var userCard models.UserCard
	if err := tx.Where("card_id = ?", req.CardID).First(&userCard).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "get_card_status_failed", err)
		return
	}

	// 更新本地卡片状态
	cardStatus := "frozen"
	if req.Status == "unfreeze" {
		cardStatus = "normal"
	}

	// 更新卡片状态
	if err := tx.Model(&models.UserCard{}).
		Where("card_id = ?", req.CardID).
		Updates(map[string]interface{}{
			"card_status": cardStatus,
			"updated_at":  time.Now(),
		}).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "update_card_status_failed", err)
		return
	}

	// 记录卡片状态变更历史
	history := models.CardStatusHistory{
		CardID:    req.CardID,
		OldStatus: userCard.CardStatus,
		NewStatus: cardStatus,
		ChangedAt: time.Now(),
		ChangedBy: "system",
		Reason:    fmt.Sprintf("Card %s via API", req.Status),
	}
	if err := tx.Create(&history).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "create_status_history_failed", err)
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "commit_transaction_failed", err)
		return
	}

	common.Success(ctx, responseData["data"])
}

// CancelCard 注销卡片
func (c *PhotonPayController) CancelCard(ctx *gin.Context) {
	var req struct {
		CardID          string  `json:"cardId" binding:"required"`
		RealTimeBalance float64 `json:"realTimeBalance" binding:"gte=0"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 检查卡片状态
	var userCard models.UserCard
	if err := c.db.Where("card_id = ?", req.CardID).First(&userCard).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			common.Error(ctx, http.StatusNotFound, "card_not_found", nil)
			return
		}
		common.Error(ctx, http.StatusInternalServerError, "get_card_status_failed", err)
		return
	}

	// 只有 normal 或 frozen 状态的卡片可以注销
	if userCard.CardStatus != "normal" && userCard.CardStatus != "frozen" {
		common.Error(ctx, http.StatusBadRequest, "card_cannot_be_cancelled", fmt.Errorf("current status: %s", userCard.CardStatus))
		return
	}

	// 获取用户角色和本地余额
	claims, exists := ctx.Get("claims")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_token_claims", nil)
		return
	}
	roleID := authClaims.RoleID
	userID := authClaims.UserID

	// 开始事务
	tx := c.db.Begin()
	if tx.Error != nil {
		common.Error(ctx, http.StatusInternalServerError, "start_transaction_failed", tx.Error)
		return
	}

	// 获取卡片的充值金额
	var totalTransferAmount float64
	if err := tx.Model(&models.UserCard{}).
		Where("card_id = ?", req.CardID).
		Select("TotalTransferAmount").
		Scan(&totalTransferAmount).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "get_card_amount_failed", err)
		return
	}

	// 根据角色返还余额
	if roleID == 3 { // 主账户
		if err := tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance + ?", totalTransferAmount)).Error; err != nil {
			tx.Rollback()
			common.Error(ctx, http.StatusInternalServerError, "update_master_balance_failed", err)
			return
		}
	} else if roleID == 5 { // 子账户
		if err := tx.Model(&models.SubAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance + ?", totalTransferAmount)).Error; err != nil {
			tx.Rollback()
			common.Error(ctx, http.StatusInternalServerError, "update_sub_balance_failed", err)
			return
		}
	}

	// 更新卡片状态和充值金额
	if err := tx.Model(&models.UserCard{}).
		Where("card_id = ?", req.CardID).
		Updates(map[string]interface{}{
			"card_status":         "closed",
			"updated_at":          time.Now(),
			"TotalTransferAmount": 0, // 将充值金额归零
		}).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "update_card_status_failed", err)
		return
	}

	// 记录卡片状态变更历史
	history := models.CardStatusHistory{
		CardID:    req.CardID,
		OldStatus: userCard.CardStatus,
		NewStatus: "closed",
		ChangedAt: time.Now(),
		ChangedBy: "system",
		Reason:    "Card cancelled via API",
	}
	if err := tx.Create(&history).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "create_status_history_failed", err)
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "commit_transaction_failed", err)
		return
	}

	// 远程注销卡片
	bodyBytes, err := json.Marshal(map[string]interface{}{
		"cardId": req.CardID,
	})
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.CancelCard(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "cancel_card_failed", err)
		return
	}

	// 解析返回的JSON数据
	var resultMap map[string]interface{}
	if err := json.Unmarshal(result, &resultMap); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	common.Success(ctx, resultMap)
}

// UpdateCard 更新卡片信息
func (c *PhotonPayController) UpdateCard(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	var req struct {
		CardID                     string   `json:"cardId" binding:"required"`
		RequestID                  string   `json:"requestId" binding:"required"`
		CardFormFactor             string   `json:"cardFormFactor" binding:"omitempty,oneof=virtual_card physical_card"`
		MaxOnDaily                 *int     `json:"maxOnDaily,omitempty"`
		MaxOnMonthly               *int     `json:"maxOnMonthly,omitempty"`
		MaxOnPercent               *int     `json:"maxOnPercent,omitempty"`
		Nickname                   string   `json:"nickname,omitempty"`
		TransactionLimit           *float64 `json:"transactionLimit,omitempty"`
		TransactionLimitType       string   `json:"transactionLimitType,omitempty" binding:"omitempty,oneof=limited unlimited"`
		TransactionLimitChangeType string   `json:"transactionLimitChangeType,omitempty" binding:"omitempty,oneof=increase decrease"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 开始事务
	tx := c.db.Begin()
	if tx.Error != nil {
		common.Error(ctx, http.StatusInternalServerError, "start_transaction_failed", tx.Error)
		return
	}

	// 如果提供了昵称，更新数据库中的 nike_name
	if req.Nickname != "" {
		if err := tx.Model(&models.UserCard{}).
			Where("card_id = ?", req.CardID).
			Update("nike_name", req.Nickname).Error; err != nil {
			tx.Rollback()
			common.Error(ctx, http.StatusInternalServerError, "update_card_nickname_failed", err)
			return
		}
	}

	// 如果传入了 transactionLimit 和 transactionLimitChangeType，则更新 TotalTransferAmount
	if req.TransactionLimit != nil && req.TransactionLimitChangeType != "" {
		var updateExpr string
		if req.TransactionLimitChangeType == "increase" {
			updateExpr = "TotalTransferAmount + ?"
		} else if req.TransactionLimitChangeType == "decrease" {
			updateExpr = "TotalTransferAmount - ?"
		} else {
			tx.Rollback()
			common.Error(ctx, http.StatusBadRequest, "invalid_transaction_limit_change_type", nil)
			return
		}
		if err := tx.Model(&models.UserCard{}).
			Where("card_id = ?", req.CardID).
			Update("TotalTransferAmount", gorm.Expr(updateExpr, *req.TransactionLimit)).Error; err != nil {
			tx.Rollback()
			common.Error(ctx, http.StatusInternalServerError, "update_transaction_limit_failed", err)
			return
		}
	}

	bodyBytes, err := json.Marshal(map[string]interface{}{
		"cardId":                     req.CardID,
		"requestId":                  req.RequestID,
		"cardFormFactor":             req.CardFormFactor,
		"maxOnDaily":                 req.MaxOnDaily,
		"maxOnMonthly":               req.MaxOnMonthly,
		"maxOnPercent":               req.MaxOnPercent,
		"nickname":                   req.Nickname,
		"transactionLimit":           req.TransactionLimit,
		"transactionLimitType":       req.TransactionLimitType,
		"transactionLimitChangeType": req.TransactionLimitChangeType,
		"matrixAccount":              matrixAccountInfo.MatrixAccount,
	})
	if err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.UpdateCard(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "update_card_failed", err)
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "commit_transaction_failed", err)
		return
	}

	// 解析返回的JSON数据
	var resultMap map[string]interface{}
	if err := json.Unmarshal(result, &resultMap); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	common.Success(ctx, resultMap)
}

// ==================== 账户管理相关接口 ====================

// GetAccountBalance 获取账户余额
func (c *PhotonPayController) GetAccountBalance(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	params := photonmodels.AccountBalanceQueryParams{
		Currency:      ctx.Query("currency"),
		AccountNo:     ctx.Query("accountNo"),
		MatrixAccount: matrixAccountInfo.MatrixAccount,
	}
	if memberId := ctx.Query("memberId"); memberId != "" {
		params.MemberID = memberId
	}
	if accountType := ctx.Query("accountType"); accountType != "" {
		params.AccountType = accountType
	}

	result, err := services.GetAccountBalance(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_account_balance_failed", err)
		return
	}

	common.Success(ctx, result)
}

// GetAccountList 查询金额账户列表
func (c *PhotonPayController) GetAccountList(ctx *gin.Context) {
	userInfo, err := c.getUserRoleAndBalance(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// 从数据库获取矩阵账户的完整信息，包括平台类型
	var userMatrixAccount models.UserMatrixAccount
	if err := c.db.Where("matrix_account = ?", matrixAccountInfo.MatrixAccount).First(&userMatrixAccount).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_matrix_account_failed", err)
		return
	}

	// 根据矩阵账户的平台类型选择不同的实现
	var result interface{}
	var err2 error

	switch userMatrixAccount.PlatformType {
	case "photonpay":
		// 使用 PhotonPay 实现
		params := photonmodels.AccountListQueryParams{
			AccountNo:     ctx.Query("accountNo"),
			MatrixAccount: matrixAccountInfo.MatrixAccount,
		}
		if memberId := ctx.Query("memberId"); memberId != "" {
			params.MemberID = memberId
		}

		result, err2 = services.GetAccountList(ctx.Request.Context(), c.client, params)
	case "hlpay":
		// 使用 HlPay 实现
		hlPayAccountBalanceService := service.NewHlPayAccountBalanceService()
		pageIndex, _ := strconv.ParseInt(ctx.DefaultQuery("pageIndex", "1"), 10, 64)
		pageSize, _ := strconv.ParseInt(ctx.DefaultQuery("pageSize", "10"), 10, 64)

		result, err2 = hlPayAccountBalanceService.GetAccountBalancesByMatrixAccount(ctx, matrixAccountInfo.MatrixAccount, pageIndex, pageSize)
	default:
		// 默认使用 PhotonPay
		params := photonmodels.AccountListQueryParams{
			AccountNo:     ctx.Query("accountNo"),
			MatrixAccount: matrixAccountInfo.MatrixAccount,
		}
		if memberId := ctx.Query("memberId"); memberId != "" {
			params.MemberID = memberId
		}

		result, err2 = services.GetAccountList(ctx.Request.Context(), c.client, params)
	}

	if err2 != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_account_list_failed", err2)
		return
	}

	// 结构体转 map，合并本地字段
	var respMap map[string]interface{}
	b, _ := json.Marshal(result)
	json.Unmarshal(b, &respMap)
	respMap["roleId"] = userInfo.RoleID

	// 查总转入
	var totalTransferAmount float64
	_ = c.db.Model(&models.UserMatrixAccount{}).
		Where("matrix_account = ?", matrixAccountInfo.MatrixAccount).
		Select("TotalTransferAmount").
		Scan(&totalTransferAmount)
	respMap["totalTransferAmount"] = totalTransferAmount

	// 根据角色设置本地余额
	respMap["localBalance"] = userInfo.Balance.InexactFloat64()

	// 如果是角色3或5，替换USD账户的realTimeBalance为localBalance
	if userInfo.RoleID == 3 || userInfo.RoleID == 5 {
		if data, ok := respMap["data"].([]interface{}); ok {
			for i, account := range data {
				if accountMap, ok := account.(map[string]interface{}); ok {
					if currency, ok := accountMap["currency"].(string); ok && currency == "USD" {
						// 保存原始的realTimeBalance
						accountMap["originalRealTimeBalance"] = accountMap["realTimeBalance"]
						// 替换为localBalance
						accountMap["realTimeBalance"] = userInfo.Balance.InexactFloat64()
						// 更新回数组
						data[i] = accountMap
					}
				}
			}
			respMap["data"] = data
		}
	}

	common.Success(ctx, respMap)
}

// GetMatrixAccountList 查询matrix账户信息
func (c *PhotonPayController) GetMatrixAccountList(ctx *gin.Context) {
	pageIndex, _ := strconv.ParseInt(ctx.DefaultQuery("pageIndex", "1"), 10, 64)
	pageSize, _ := strconv.ParseInt(ctx.DefaultQuery("pageSize", "10"), 10, 64)
	params := photonmodels.MatrixAccountQueryParams{
		PageIndex:      pageIndex,
		PageSize:       pageSize,
		CreatedAtStart: ctx.Query("createdAtStart"),
		CreatedAtEnd:   ctx.Query("createdAtEnd"),
	}

	result, err := services.GetMatrixAccountList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_account_list_failed", err)
		return
	}

	common.Success(ctx, result)
}

// CreateMatrixAccount 创建matrix账户
func (c *PhotonPayController) CreateMatrixAccount(ctx *gin.Context) {
	bodyBytes, err := ctx.GetRawData()
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	result, err := services.CreateMatrixAccount(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "create_matrix_account_failed", err)
		return
	}
	resultMap := make(map[string]interface{})
	err = json.Unmarshal(result, &resultMap)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	common.Success(ctx, resultMap["data"])
}

// EditMatrixAccount 编辑matrix账户信息
func (c *PhotonPayController) EditMatrixAccount(ctx *gin.Context) {
	bodyBytes, err := ctx.GetRawData()
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	result, err := services.EditMatrixAccount(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "edit_matrix_account_failed", err)
		return
	}
	resultMap := make(map[string]interface{})
	err = json.Unmarshal(result, &resultMap)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	common.Success(ctx, resultMap["data"])
}

// ==================== 交易相关接口 ====================

// Recharge 转入下单
func (c *PhotonPayController) Recharge(ctx *gin.Context) {
	var req struct {
		RequestId string      `json:"requestId" binding:"required"`
		CardId    string      `json:"cardId" binding:"required"`
		CardID    string      `json:"CardId"`                    // 支持大写CardId
		Amount    interface{} `json:"amount" binding:"required"` // 支持string和float64
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 处理CardId字段，支持两种大小写
	cardId := req.CardId
	if cardId == "" {
		cardId = req.CardID
	}

	// 处理Amount字段，支持字符串和数字
	var amount float64
	switch v := req.Amount.(type) {
	case string:
		var err error
		amount, err = strconv.ParseFloat(v, 64)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_amount_format", err)
			return
		}
	case float64:
		amount = v
	case int:
		amount = float64(v)
	case int64:
		amount = float64(v)
	default:
		common.Error(ctx, http.StatusBadRequest, "invalid_amount_type", fmt.Errorf("amount must be string or number, got %T", req.Amount))
		return
	}

	// 获取用户角色和余额信息
	userInfo, err := c.getUserRoleAndBalance(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// Start a transaction
	tx := c.db.Begin()
	if tx.Error != nil {
		common.Error(ctx, http.StatusInternalServerError, "start_transaction_failed", tx.Error)
		return
	}

	// 先查卡是否存在
	var userCard models.UserCard
	if err := tx.Where("card_id = ?", cardId).First(&userCard).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusBadRequest, "card_not_found", err)
		return
	}

	// 检查并扣除余额
	if err := c.checkAndDeductBalance(tx, userInfo.RoleID, userInfo.UserID, amount); err != nil {
		tx.Rollback()
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// 只对已存在卡做累加
	if err := tx.Model(&models.UserCard{}).
		Where("card_id = ?", cardId).
		UpdateColumn("TotalTransferAmount", gorm.Expr("TotalTransferAmount + ?", amount)).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "update_transfer_amount_failed", err)
		return
	}

	// Commit the transaction
	if err := tx.Commit().Error; err != nil {
		log.Printf("[Recharge] Commit transaction failed: %v", err)
		common.Error(ctx, http.StatusInternalServerError, "commit_transaction_failed", err)
		return
	}
	log.Printf("[Recharge] Transaction committed successfully")

	// 构造请求体，确保字段名正确
	requestBody := map[string]interface{}{
		"requestId": req.RequestId,
		"cardId":    cardId,
		"amount":    amount,
	}

	bodyBytes, err := json.Marshal(requestBody)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.Recharge(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "recharge_failed", err)
		return
	}

	// 解析返回的JSON数据
	var respMap map[string]interface{}
	if err := json.Unmarshal(result, &respMap); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	// 检查响应状态
	if code, ok := respMap["code"].(string); ok && code != "200" {
		// 返回错误响应
		ctx.JSON(http.StatusOK, respMap)
		return
	}

	// 充值成功后，查本地 user_cards 表的 TotalTransferAmount 并补充到返回数据
	err = c.db.Where("card_id = ?", cardId).First(&userCard).Error
	log.Printf("[Recharge] After update, userCard.TotalTransferAmount=%v, err=%v", userCard.TotalTransferAmount, err)
	if err == nil {
		// 兼容嵌套结构
		if data, ok := respMap["data"].(map[string]interface{}); ok {
			data["totalTransferAmount"] = userCard.TotalTransferAmount
		} else {
			respMap["totalTransferAmount"] = userCard.TotalTransferAmount
		}
	}

	ctx.JSON(http.StatusOK, respMap)
}

// PreRecharge 预充值
func (c *PhotonPayController) PreRecharge(ctx *gin.Context) {
	// 获取参数
	params := map[string]string{
		"accountId":      ctx.Query("accountId"),
		"cardId":         ctx.Query("cardId"),
		"rechargeAmount": ctx.Query("rechargeAmount"),
		"requestId":      ctx.Query("requestId"),
	}

	// 验证参数
	if params["accountId"] == "" || params["cardId"] == "" || params["rechargeAmount"] == "" || params["requestId"] == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": "400",
			"msg": map[string]string{
				"CN": "参数不完整",
				"EN": "Incomplete parameters",
				"VN": "Tham số không đầy đủ",
			},
		})
		return
	}

	// 发送请求
	result, err := services.PreRecharge(ctx.Request.Context(), c.client, params)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": "500",
			"msg": map[string]string{
				"CN": "预充值失败",
				"EN": "Pre-recharge failed",
				"VN": "Nạp tiền trước thất bại",
			},
			"error": err.Error(),
		})
		return
	}

	// 直接返回响应
	ctx.Data(http.StatusOK, "application/json", result)
}

// RechargeReturn 卡金额退还
func (c *PhotonPayController) RechargeReturn(ctx *gin.Context) {
	var req struct {
		CardId       string `json:"cardId" binding:"required"`
		ReturnAmount string `json:"returnAmount" binding:"required"`
		RequestId    string `json:"requestId" binding:"required"`
	}

	// 1. 参数验证
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	// 2. 转换金额并验证格式
	returnAmount, err := decimal.NewFromString(req.ReturnAmount)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_amount_format", err)
		return
	}

	// 3. 查询卡片信息
	var userCard models.UserCard
	if err := c.db.Where("card_id = ?", req.CardId).First(&userCard).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			common.Error(ctx, http.StatusNotFound, "card_not_found", fmt.Errorf("card %s not found", req.CardId))
		} else {
			common.Error(ctx, http.StatusInternalServerError, "query_card_failed", err)
		}
		return
	}

	// 4. 验证退还金额
	if userCard.TotalTransferAmount.LessThan(returnAmount) {
		common.Error(ctx, http.StatusBadRequest, "refund_amount_exceeds_total",
			fmt.Errorf("refund amount %s exceeds total transfer amount %s",
				returnAmount.String(), userCard.TotalTransferAmount.String()))
		return
	}

	// 5. 获取用户信息
	userInfo, err := c.getUserRoleAndBalance(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// 6. 先更新本地数据库，确保数据一致性
	tx := c.db.Begin()
	if tx.Error != nil {
		common.Error(ctx, http.StatusInternalServerError, "start_transaction_failed", tx.Error)
		return
	}
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 7. 根据用户角色更新账户余额
	if err := c.updateAccountBalance(tx, userInfo, returnAmount); err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, err.Error(), nil)
		return
	}

	// 8. 更新卡片总转账金额
	if err := tx.Model(&models.UserCard{}).
		Where("card_id = ?", req.CardId).
		Update("`TotalTransferAmount`", gorm.Expr("`TotalTransferAmount` - ?", returnAmount)).Error; err != nil {
		tx.Rollback()
		common.Error(ctx, http.StatusInternalServerError, "update_transfer_amount_failed", err)
		return
	}

	// 9. 提交本地数据库事务
	if err := tx.Commit().Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "commit_transaction_failed", err)
		return
	}

	// 10. 调用远程退还接口
	bodyBytes, err := json.Marshal(req)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.RechargeReturn(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		// 远程接口调用失败，但本地数据库已更新
		// 记录错误日志，但不回滚本地更新
		log.Printf("Remote recharge return failed for card %s: %v, but local database has been updated", req.CardId, err)

		// 尝试解析错误响应
		var errorResponse struct {
			Code string `json:"code"`
			Msg  string `json:"msg"`
			Data string `json:"data"`
		}
		if err := json.Unmarshal([]byte(err.Error()), &errorResponse); err == nil {
			ctx.JSON(http.StatusOK, gin.H{
				"code": errorResponse.Code,
				"msg":  errorResponse.Msg,
				"data": errorResponse.Data,
				"note": "Local database updated successfully, but remote operation failed",
			})
			return
		}

		// 返回成功响应，因为本地数据库已更新
		common.Success(ctx, gin.H{
			"code": "0000",
			"msg":  "Local refund completed successfully",
			"data": gin.H{
				"cardId":       req.CardId,
				"returnAmount": req.ReturnAmount,
				"note":         "Remote operation failed, but local database has been updated",
			},
		})
		return
	}

	// 11. 解析远程接口响应
	var resultMap map[string]interface{}
	if err := json.Unmarshal(result, &resultMap); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	// 检查远程接口响应状态
	if code, ok := resultMap["code"].(string); !ok || code != "0000" {
		// 远程接口返回错误，但本地数据库已更新
		log.Printf("Remote recharge return returned error code %s for card %s, but local database has been updated", code, req.CardId)

		ctx.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  resultMap["msg"],
			"data": resultMap["data"],
			"note": "Local database updated successfully, but remote operation returned error",
		})
		return
	}

	// 12. 返回成功响应
	common.Success(ctx, gin.H{
		"code": "0000",
		"msg":  "Refund completed successfully",
		"data": resultMap,
		"local_update": gin.H{
			"cardId":       req.CardId,
			"returnAmount": req.ReturnAmount,
			"status":       "completed",
		},
	})
}

// updateAccountBalance 根据用户角色更新账户余额
func (c *PhotonPayController) updateAccountBalance(tx *gorm.DB, userInfo *PhotonPayUserRoleBalance, amount decimal.Decimal) error {
	switch userInfo.RoleID {
	case 2: // 普通用户 - 不需要处理余额
		return nil
	case 3: // 主账号
		return tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", userInfo.UserID).
			Update("balance", gorm.Expr("balance + ?", amount)).Error
	case 5: // 子账号
		return tx.Model(&models.SubAccount{}).
			Where("user_id = ?", userInfo.UserID).
			Update("balance", gorm.Expr("balance + ?", amount)).Error
	default:
		return fmt.Errorf("invalid_user_role: %d", userInfo.RoleID)
	}
}

// MatrixTransfer 矩阵转账
func (c *PhotonPayController) MatrixTransfer(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	var req struct {
		Currency       string `json:"currency" binding:"required"`
		MatrixAccount  string `json:"matrixAccount" binding:"required"`
		TransferAmount string `json:"transferAmount" binding:"required"`
		TransferType   string `json:"transferType" binding:"required,oneof=transfer_in transfer_out"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	amount, err := strconv.ParseFloat(req.TransferAmount, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_amount_format", err)
		return
	}
	if amount <= 0 {
		common.Error(ctx, http.StatusBadRequest, "invalid_amount", nil)
		return
	}

	bodyBytes, err := json.Marshal(map[string]interface{}{
		"transferAmount": req.TransferAmount,
		"currency":       req.Currency,
		"matrixAccount":  req.MatrixAccount,
		"transferType":   req.TransferType,
	})
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.MatrixTransfer(ctx.Request.Context(), c.client, bodyBytes)
	fmt.Println("矩阵转账结果", string(result))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "transfer_failed", err)
		return
	}

	resultMap := make(map[string]interface{})
	err = json.Unmarshal(result, &resultMap)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "parse_result_failed", err)
		return
	}

	if code, ok := resultMap["code"].(string); !ok || code != "0000" {
		common.Error(ctx, http.StatusInternalServerError, "transfer_failed", fmt.Errorf("code: %v, msg: %v", code, resultMap["msg"]))
		return
	}

	// 记录交易信息
	transaction := &models.Transaction{
		TransactionID:   fmt.Sprintf("MT%d", time.Now().UnixNano()),
		CardID:          "SYSTEM",
		TransactionType: payment.TransactionTypeMatrixTransfer,
		Amount:          amount,
		Currency:        req.Currency,
		Status:          payment.TransactionStatusCompleted,
		MatrixAccount:   matrixAccountInfo.MatrixAccount,
		Platform:        "photonpay",
		RawData:         models.JSONMap(resultMap),
		ProcessedAt:     time.Now(),
	}

	if err := c.db.Create(transaction).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "record_transaction_failed", err)
		return
	}

	var updateAmount float64
	if req.TransferType == "transfer_in" {
		updateAmount = amount
	} else {
		updateAmount = -amount
	}

	// 更新矩阵账户的转账总额
	if err := c.db.Model(&models.UserMatrixAccount{}).
		Where("matrix_account = ? AND status = 'active'", matrixAccountInfo.MatrixAccount).
		Update("TotalTransferAmount", gorm.Expr("TotalTransferAmount + ?", updateAmount)).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "update_transfer_amount_failed", err)
		return
	}

	// 为每个订单添加卡片昵称
	for i := range resultMap["data"].([]interface{}) {
		order := resultMap["data"].([]interface{})[i].(map[string]interface{})
		cardID := order["cardId"].(string)
		var userCard models.UserCard
		if err := c.db.Where("card_id = ?", cardID).First(&userCard).Error; err == nil {
			order["cardNickname"] = userCard.NikeName
		}
	}

	// 计算统计数据
	transactionTypeStats := make(map[string]map[string]interface{})
	cardTypeStats := make(map[string]int)
	cardFormFactorStats := make(map[string]int)
	var totalAmount float64
	var totalFee float64

	for _, order := range resultMap["data"].([]interface{}) {
		orderMap := order.(map[string]interface{})
		cardType := orderMap["cardType"].(string)
		cardFormFactor := orderMap["cardFormFactor"].(string)
		transactionType := orderMap["transactionType"].(string)
		transactionAmount := orderMap["transactionAmount"].(float64)
		feeDeductionAmount := orderMap["feeDeductionAmount"].(float64)

		// 统计交易类型
		if _, exists := transactionTypeStats[transactionType]; !exists {
			transactionTypeStats[transactionType] = map[string]interface{}{
				"count":        0,
				"total_amount": 0.0,
				"total_fee":    0.0,
			}
		}
		stats := transactionTypeStats[transactionType]
		stats["count"] = stats["count"].(int) + 1
		stats["total_amount"] = stats["total_amount"].(float64) + transactionAmount
		if feeDeductionAmount != 0 {
			stats["total_fee"] = stats["total_fee"].(float64) + feeDeductionAmount
		}

		// 统计卡片类型
		cardTypeStats[cardType]++

		// 统计卡片形式
		cardFormFactorStats[cardFormFactor]++

		// 累计总金额和费用
		totalAmount += transactionAmount
		if feeDeductionAmount != 0 {
			totalFee += feeDeductionAmount
		}
	}

	// 添加统计数据到响应中
	statistics := map[string]interface{}{
		"total_transactions":  len(resultMap["data"].([]interface{})),
		"total_amount":        totalAmount,
		"total_fee":           totalFee,
		"by_transaction_type": transactionTypeStats,
		"by_card_type":        cardTypeStats,
		"by_card_form_factor": cardFormFactorStats,
	}

	// 构建最终响应
	response := map[string]interface{}{
		"code":       "0000",
		"msg":        "success",
		"data":       resultMap["data"],
		"pageIndex":  resultMap["pageIndex"],
		"pageSize":   resultMap["pageSize"],
		"total":      resultMap["total"],
		"statistics": statistics,
	}

	common.Success(ctx, response)
}

// ==================== 持卡人管理相关接口 ====================

// GetCardholderList 获取持卡人列表
func (c *PhotonPayController) GetCardholderList(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// 获取查询参数
	name := ctx.Query("name")
	page, pageSize := common.GetPaginationParams(ctx)

	// 构建查询参数
	params := photonmodels.CardholderQueryParams{
		PageIndex:     1,   // 先获取第一页
		PageSize:      100, // 获取较大的数据量以支持本地过滤
		MatrixAccount: matrixAccountInfo.MatrixAccount,
		Name:          name, // 添加name参数支持API级别的过滤
	}

	// 获取所有持卡人数据
	result, err := services.GetCardholderList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_cardholder_list_failed", err)
		return
	}

	// 如果有名称搜索条件，进行本地过滤
	if name != "" {
		name = strings.ToUpper(name) // 转换为大写以匹配API返回的数据格式
		var filteredData []photonmodels.CardholderInfo
		for _, cardholder := range result.Data {
			// 检查firstName或lastName是否包含搜索词
			if strings.Contains(cardholder.FirstName, name) || strings.Contains(cardholder.LastName, name) {
				filteredData = append(filteredData, cardholder)
			}
		}
		result.Data = filteredData
		result.Total = int64(len(filteredData))
	}

	// 计算分页
	start := int((page - 1) * pageSize)
	end := start + int(pageSize)
	if start >= len(result.Data) {
		result.Data = []photonmodels.CardholderInfo{}
	} else if end > len(result.Data) {
		result.Data = result.Data[start:]
	} else {
		result.Data = result.Data[start:end]
	}

	// 更新分页信息
	result.PageIndex = page
	result.PageSize = pageSize

	common.Success(ctx, result)
}

// AddCardholder 添加用卡人
func (c *PhotonPayController) AddCardholder(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	bodyBytes, err := ctx.GetRawData()
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	var requestBody map[string]interface{}
	if err := json.Unmarshal(bodyBytes, &requestBody); err != nil {
		common.Error(ctx, http.StatusBadRequest, "json_format_error", err)
		return
	}

	requestBody["matrixAccount"] = matrixAccountInfo.MatrixAccount
	requestBody["matrixAccountName"] = matrixAccountInfo.MatrixAccountName

	bodyBytes, err = json.Marshal(requestBody)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.AddCardholder(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "add_cardholder_failed", err)
		return
	}

	common.Success(ctx, result)
}

// EditCardholder 用卡人更新
func (c *PhotonPayController) EditCardholder(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	bodyBytes, err := ctx.GetRawData()
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	var requestBody map[string]interface{}
	if err := json.Unmarshal(bodyBytes, &requestBody); err != nil {
		common.Error(ctx, http.StatusBadRequest, "json_format_error", err)
		return
	}

	requestBody["matrixAccount"] = matrixAccountInfo.MatrixAccount
	requestBody["matrixAccountName"] = matrixAccountInfo.MatrixAccountName

	bodyBytes, err = json.Marshal(requestBody)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.EditCardholder(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "edit_cardholder_failed", err)
		return
	}

	common.Success(ctx, result)
}

// ==================== 交易记录查询相关接口 ====================

// GetVccTradeOrderList 获取VCC交易订单列表
func (c *PhotonPayController) GetVccTradeOrderList(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// 获取用户ID和角色
	claims, exists := ctx.Get("claims")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_token_claims", nil)
		return
	}
	userID := authClaims.UserID
	roleID := authClaims.RoleID

	// 如果是子账号(role_id=5)，需要获取用户的所有卡片ID并进行过滤
	var userCards []models.UserCard
	if roleID == 5 {
		if err := c.db.Where("user_id = ?", userID).Find(&userCards).Error; err != nil {
			common.Error(ctx, http.StatusInternalServerError, "get_user_cards_failed", err)
			return
		}

		// 如果没有卡片，直接返回空结果
		if len(userCards) == 0 {
			common.Success(ctx, gin.H{
				"code":      "0000",
				"msg":       "success",
				"data":      []interface{}{},
				"pageIndex": 1,
				"pageSize":  100,
				"total":     0,
			})
			return
		}

		// 如果指定了特定卡片ID，验证该卡片是否属于当前用户
		if requestedCardID := ctx.Query("cardId"); requestedCardID != "" {
			isValid := false
			for _, card := range userCards {
				if card.CardID == requestedCardID {
					isValid = true
					break
				}
			}
			if !isValid {
				common.Error(ctx, http.StatusForbidden, "card_not_belong_to_user", nil)
				return
			}
		}
	}

	page, pageSize := common.GetPaginationParams(ctx)

	// 处理多个交易类型和状态
	transactionTypes := strings.Split(ctx.Query("transactionType"), ",")
	statuses := strings.Split(ctx.Query("status"), ",")

	// 过滤掉空字符串
	var filteredTransactionTypes []string
	for _, t := range transactionTypes {
		if t != "" {
			filteredTransactionTypes = append(filteredTransactionTypes, strings.TrimSpace(t))
		}
	}

	var filteredStatuses []string
	for _, s := range statuses {
		if s != "" {
			filteredStatuses = append(filteredStatuses, strings.TrimSpace(s))
		}
	}

	params := photonmodels.VccTradeOrderQueryParams{
		PageIndex:       page,
		PageSize:        pageSize,
		MatrixAccount:   matrixAccountInfo.MatrixAccount,
		CardID:          ctx.Query("cardId"),
		CardType:        ctx.Query("cardType"),
		RequestID:       ctx.Query("requestId"),
		TransactionID:   ctx.Query("transactionId"),
		Status:          strings.Join(filteredStatuses, ","),         // 使用逗号连接多个状态
		TransactionType: strings.Join(filteredTransactionTypes, ","), // 使用逗号连接多个交易类型
		CreatedAtStart:  ctx.Query("createdAtStart"),
		CreatedAtEnd:    ctx.Query("createdAtEnd"),
		CardNickname:    ctx.Query("cardNickname"), // 添加卡片昵称查询条件
	}

	// 打印查询参数，用于调试
	fmt.Printf("查询参数: %+v\n", params)

	// 获取语言参数
	language := ctx.Query("language")

	// 创建上下文
	var ctxWithLang context.Context
	if language == "" {
		// 如果language为空，不传递语言参数，保持原始上下文
		ctxWithLang = ctx.Request.Context()
	} else {
		// 如果language不为空，转换为大写并传递语言参数
		language = strings.ToUpper(language)
		ctxWithLang = context.WithValue(ctx.Request.Context(), "language", language)
	}

	result, err := services.GetVccTradeOrderList(ctxWithLang, c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_vcc_trade_failed", err)
		return
	}

	// 如果是子账号，需要过滤结果
	if roleID == 5 {
		// 过滤结果，只保留用户拥有的卡片的交易记录
		filteredData := make([]photonmodels.VccTradeOrderInfo, 0)
		for _, order := range result.Data {
			for _, card := range userCards {
				if order.CardID == card.CardID {
					order.CardNickname = card.NikeName
					filteredData = append(filteredData, order)
					break
				}
			}
		}

		// 更新结果
		result.Data = filteredData
		result.Total = int64(len(filteredData))
	} else {
		// 对于管理员和主账号，获取所有卡片的昵称
		cardIDs := make([]string, 0)
		for _, order := range result.Data {
			if order.CardID != "" {
				cardIDs = append(cardIDs, order.CardID)
			}
		}

		// 从数据库中查询卡片昵称
		var cards []models.UserCard
		if err := c.db.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
			common.Error(ctx, http.StatusInternalServerError, "query_card_nicknames_failed", err)
			return
		}

		// 创建卡片ID到昵称的映射
		cardNicknames := make(map[string]string)
		for _, card := range cards {
			cardNicknames[card.CardID] = card.NikeName
		}

		// 为每个订单添加卡片昵称
		for i := range result.Data {
			if nickname, exists := cardNicknames[result.Data[i].CardID]; exists {
				result.Data[i].CardNickname = nickname
			}
		}
	}

	// 根据cardNickname进行本地过滤
	if cardNickname := ctx.Query("cardNickname"); cardNickname != "" {
		filteredData := make([]photonmodels.VccTradeOrderInfo, 0)
		for _, order := range result.Data {
			// 使用模糊匹配，支持部分匹配
			if strings.Contains(strings.ToLower(order.CardNickname), strings.ToLower(cardNickname)) {
				filteredData = append(filteredData, order)
			}
		}
		result.Data = filteredData
		result.Total = int64(len(filteredData))
	}

	// 计算统计数据
	transactionTypeStats := make(map[string]map[string]interface{})
	cardTypeStats := make(map[string]int)
	cardFormFactorStats := make(map[string]int)
	var totalAmount float64
	var totalFee float64

	for _, order := range result.Data {
		// 统计交易类型
		if _, exists := transactionTypeStats[order.TransactionType]; !exists {
			transactionTypeStats[order.TransactionType] = map[string]interface{}{
				"count":        0,
				"total_amount": 0.0,
				"total_fee":    0.0,
			}
		}
		stats := transactionTypeStats[order.TransactionType]
		stats["count"] = stats["count"].(int) + 1
		stats["total_amount"] = stats["total_amount"].(float64) + float64(order.TransactionAmount)
		if order.FeeDeductionAmount != 0 {
			stats["total_fee"] = stats["total_fee"].(float64) + float64(order.FeeDeductionAmount)
		}

		// 统计卡片类型
		cardTypeStats[order.CardType]++

		// 统计卡片形式
		cardFormFactorStats[order.CardFormFactor]++

		// 累计总金额和费用
		totalAmount += float64(order.TransactionAmount)
		if order.FeeDeductionAmount != 0 {
			totalFee += float64(order.FeeDeductionAmount)
		}
	}

	// 添加统计数据到响应中
	statistics := map[string]interface{}{
		"total_transactions":  len(result.Data),
		"total_amount":        totalAmount,
		"total_fee":           totalFee,
		"by_transaction_type": transactionTypeStats,
		"by_card_type":        cardTypeStats,
		"by_card_form_factor": cardFormFactorStats,
	}

	// 构建最终响应
	response := map[string]interface{}{
		"code":       "0000",
		"msg":        "success",
		"data":       result.Data,
		"pageIndex":  result.PageIndex,
		"pageSize":   result.PageSize,
		"total":      result.Total,
		"statistics": statistics,
	}

	common.Success(ctx, response)
}

// GetAccountHistoryList 获取账户历史列表
func (c *PhotonPayController) GetAccountHistoryList(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	page, pageSize := common.GetPaginationParams(ctx)
	params := photonmodels.AccountHistoryQueryParams{
		PageIndex:     page,
		PageSize:      pageSize,
		MatrixAccount: matrixAccountInfo.MatrixAccount,
	}

	result, err := services.GetAccountHistoryList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_account_history_failed", err)
		return
	}

	common.Success(ctx, result)
}

// GetFundTransferList 查询资金调拨明细
func (c *PhotonPayController) GetFundTransferList(ctx *gin.Context) {
	matrixInfo, exists := ctx.Get("matrix_account_info")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "matrix_account_not_found", nil)
		return
	}

	if _, ok := matrixInfo.(map[string]interface{}); !ok {
		common.Error(ctx, http.StatusInternalServerError, "matrix_account_invalid", nil)
		return
	}

	pageIndex, _ := strconv.ParseInt(ctx.DefaultQuery("pageIndex", "1"), 10, 64)
	pageSize, _ := strconv.ParseInt(ctx.DefaultQuery("pageSize", "10"), 10, 64)
	params := photonmodels.FundTransferListQueryParams{
		PageIndex:        pageIndex,
		PageSize:         pageSize,
		CreatedAtStart:   ctx.Query("createdAtStart"),
		CreatedAtEnd:     ctx.Query("createdAtEnd"),
		CompletedAtStart: ctx.Query("completedAtStart"),
		CompletedAtEnd:   ctx.Query("completedAtEnd"),
		Status:           ctx.Query("status"),
		RequestNo:        ctx.Query("requestNo"),
		TransactionId:    ctx.Query("transactionId"),
		Direction:        ctx.Query("direction"),
		MemberId:         ctx.Query("memberId"),
	}

	result, err := services.GetFundTransferList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_fund_transfer_failed", err)
		return
	}

	common.Success(ctx, result)
}

// GetIssuingHistoryList 获取发卡历史列表
func (c *PhotonPayController) GetIssuingHistoryList(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	// 获取用户ID和角色
	claims, exists := ctx.Get("claims")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_token_claims", nil)
		return
	}
	userID := authClaims.UserID
	roleID := authClaims.RoleID

	// 如果是子账号(role_id=5)，需要获取用户的所有卡片ID并进行过滤
	var userCards []models.UserCard
	if roleID == 5 {
		if err := c.db.Where("user_id = ?", userID).Find(&userCards).Error; err != nil {
			common.Error(ctx, http.StatusInternalServerError, "get_user_cards_failed", err)
			return
		}

		// 如果没有卡片，直接返回空结果
		if len(userCards) == 0 {
			common.Success(ctx, gin.H{
				"code":      "0000",
				"msg":       "success",
				"data":      []interface{}{},
				"pageIndex": 1,
				"pageSize":  100,
				"total":     0,
			})
			return
		}

		// 如果指定了特定卡片ID，验证该卡片是否属于当前用户
		if cardID := ctx.Query("cardId"); cardID != "" {
			isValid := false
			for _, card := range userCards {
				if card.CardID == cardID {
					isValid = true
					break
				}
			}
			if !isValid {
				common.Error(ctx, http.StatusForbidden, "card_not_belong_to_user", nil)
				return
			}
		}
	}

	page, pageSize := common.GetPaginationParams(ctx)

	// 处理多个收费类型和状态
	feeTypes := strings.Split(ctx.Query("feeType"), ",")
	statuses := strings.Split(ctx.Query("status"), ",")

	// 过滤掉空字符串
	var filteredFeeTypes []string
	for _, t := range feeTypes {
		if t != "" {
			filteredFeeTypes = append(filteredFeeTypes, strings.TrimSpace(t))
		}
	}

	var filteredStatuses []string
	for _, s := range statuses {
		if s != "" {
			filteredStatuses = append(filteredStatuses, strings.TrimSpace(s))
		}
	}

	params := photonmodels.IssuingHistoryQueryParams{
		PageIndex:      page,
		PageSize:       pageSize,
		MatrixAccount:  matrixAccountInfo.MatrixAccount,
		CardID:         ctx.Query("cardId"),
		CardFormFactor: ctx.Query("cardFormFactor"),
		Status:         strings.Join(filteredStatuses, ","), // 使用逗号连接多个状态
		FeeType:        strings.Join(filteredFeeTypes, ","), // 使用逗号连接多个收费类型
		CreatedAtStart: ctx.Query("createdAtStart"),
		CreatedAtEnd:   ctx.Query("createdAtEnd"),
	}

	// 打印查询参数，用于调试
	fmt.Printf("查询参数: %+v\n", params)

	result, err := services.GetIssuingHistoryList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_issuing_history_failed", err)
		return
	}

	// 如果是子账号，需要过滤结果
	if roleID == 5 {
		// 过滤结果，只保留用户拥有的卡片的记录
		filteredData := make([]photonmodels.IssuingHistoryInfo, 0)
		for _, record := range result.Data {
			for _, card := range userCards {
				if record.CardID == card.CardID {
					record.CardNickname = card.NikeName
					filteredData = append(filteredData, record)
					break
				}
			}
		}

		// 更新结果
		result.Data = filteredData
		result.Total = int64(len(filteredData))
	} else {
		// 对于管理员和主账号，获取所有卡片的昵称
		cardIDs := make([]string, 0)
		for _, record := range result.Data {
			if record.CardID != "" {
				cardIDs = append(cardIDs, record.CardID)
			}
		}

		// 从数据库中查询卡片昵称
		var cards []models.UserCard
		if err := c.db.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
			common.Error(ctx, http.StatusInternalServerError, "query_card_nicknames_failed", err)
			return
		}

		// 创建卡片ID到昵称的映射
		cardNicknames := make(map[string]string)
		for _, card := range cards {
			cardNicknames[card.CardID] = card.NikeName
		}

		// 为每个记录添加卡片昵称
		for i := range result.Data {
			if nickname, exists := cardNicknames[result.Data[i].CardID]; exists {
				result.Data[i].CardNickname = nickname
			}
		}
	}

	// 计算统计数据
	transactionTypeStats := make(map[string]map[string]interface{})
	cardTypeStats := make(map[string]int)
	cardFormFactorStats := make(map[string]int)
	var totalAmount float64
	var totalFee float64

	for _, record := range result.Data {
		// 统计交易类型
		if _, exists := transactionTypeStats[record.FeeType]; !exists {
			transactionTypeStats[record.FeeType] = map[string]interface{}{
				"count":        0,
				"total_amount": 0.0,
				"total_fee":    0.0,
			}
		}
		stats := transactionTypeStats[record.FeeType]
		stats["count"] = stats["count"].(int) + 1

		// 转换费用金额
		if amount, err := strconv.ParseFloat(record.ActualFeeAmount, 64); err == nil {
			stats["total_amount"] = stats["total_amount"].(float64) + amount
			totalAmount += amount
		}

		// 统计卡片类型
		cardTypeStats[record.CardType]++

		// 统计卡片形式
		cardFormFactorStats[record.CardFormFactor]++
	}

	// 添加统计数据到响应中
	statistics := map[string]interface{}{
		"total_transactions":  len(result.Data),
		"total_amount":        totalAmount,
		"total_fee":           totalFee,
		"by_transaction_type": transactionTypeStats,
		"by_card_type":        cardTypeStats,
		"by_card_form_factor": cardFormFactorStats,
	}

	// 构建最终响应
	response := map[string]interface{}{
		"code":       "0000",
		"msg":        "success",
		"data":       result.Data,
		"pageIndex":  result.PageIndex,
		"pageSize":   result.PageSize,
		"total":      result.Total,
		"statistics": statistics,
	}

	common.Success(ctx, response)
}

// GetRechargeCardFundsDetailList 获取充值卡资金明细列表
func (c *PhotonPayController) GetRechargeCardFundsDetailList(ctx *gin.Context) {
	matrixAccountInfo, err := c.getMatrixAccountFromToken(ctx)
	if err != nil {
		common.Error(ctx, err.(*errors.AppError).Code, err.Error(), nil)
		return
	}

	page, pageSize := common.GetPaginationParams(ctx)
	params := photonmodels.VccTradeOrderQueryParams{
		PageIndex:     page,
		PageSize:      pageSize,
		MatrixAccount: matrixAccountInfo.MatrixAccount,
		CardID:        ctx.Query("cardId"),
	}

	result, err := services.GetVccTradeOrderList(ctx.Request.Context(), c.client, params)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_recharge_funds_failed", err)
		return
	}

	common.Success(ctx, result)
}

// GetAccountListByMatrixAccount 根据矩阵账户查询金额账户列表
func (c *PhotonPayController) GetAccountListByMatrixAccount(ctx *gin.Context) {
	// 获取指定的矩阵账户
	matrixAccount := ctx.Query("matrixAccount")
	if matrixAccount == "" {
		common.Error(ctx, http.StatusBadRequest, "matrix_account_required", fmt.Errorf("matrixAccount parameter is required"))
		return
	}

	// 从数据库获取矩阵账户的完整信息，包括平台类型
	var userMatrixAccount models.UserMatrixAccount
	if err := c.db.Where("matrix_account = ?", matrixAccount).First(&userMatrixAccount).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_matrix_account_failed", err)
		return
	}

	// 根据矩阵账户的平台类型选择不同的实现
	var result interface{}
	var err error

	switch userMatrixAccount.PlatformType {
	case "photonpay":
		// 使用 PhotonPay 实现
		params := photonmodels.AccountListQueryParams{
			AccountNo:     ctx.Query("accountNo"),
			MatrixAccount: matrixAccount,
		}
		if memberId := ctx.Query("memberId"); memberId != "" {
			params.MemberID = memberId
		}

		result, err = services.GetAccountList(ctx.Request.Context(), c.client, params)
	case "hlpay":
		// 使用 HlPay 实现
		hlPayAccountBalanceService := service.NewHlPayAccountBalanceService()
		pageIndex, _ := strconv.ParseInt(ctx.DefaultQuery("pageIndex", "1"), 10, 64)
		pageSize, _ := strconv.ParseInt(ctx.DefaultQuery("pageSize", "10"), 10, 64)

		result, err = hlPayAccountBalanceService.GetAccountBalancesByMatrixAccount(ctx, matrixAccount, pageIndex, pageSize)
	default:
		// 默认使用 PhotonPay
		params := photonmodels.AccountListQueryParams{
			AccountNo:     ctx.Query("accountNo"),
			MatrixAccount: matrixAccount,
		}
		if memberId := ctx.Query("memberId"); memberId != "" {
			params.MemberID = memberId
		}

		result, err = services.GetAccountList(ctx.Request.Context(), c.client, params)
	}

	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_account_list_failed", err)
		return
	}

	common.Success(ctx, result)
}

// GetCardCVV 获取卡片CVV
func (c *PhotonPayController) GetCardCVV(ctx *gin.Context) {
	// 获取卡片ID
	cardID := ctx.Query("cardId")
	if cardID == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": "400",
			"msg": map[string]string{
				"CN": "卡片ID不能为空",
				"EN": "Card ID cannot be empty",
				"VN": "ID thẻ không được để trống",
			},
		})
		return
	}

	// 获取CVV
	result, err := services.GetCardCVV(ctx.Request.Context(), c.client, cardID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": "500",
			"msg": map[string]string{
				"CN": "获取CVV失败",
				"EN": "Failed to get CVV",
				"VN": "Không thể lấy CVV",
			},
			"error": err.Error(),
		})
		return
	}

	// 直接返回响应
	ctx.Data(http.StatusOK, "application/json", result)
}

// SimulateTransaction 模拟交易
func (c *PhotonPayController) SimulateTransaction(ctx *gin.Context) {
	var req struct {
		RequestID           string  `json:"requestId" binding:"required"`
		CardID              string  `json:"cardID" binding:"required"`
		CVV                 string  `json:"cvv" binding:"required"`
		ExpirationDate      string  `json:"expirationDate" binding:"required"`
		OriginTransactionID string  `json:"originTransactionId"`
		TxnCurrency         string  `json:"txnCurrency" binding:"required"`
		TxnAmount           float64 `json:"txnAmount" binding:"required"`
		TxnType             string  `json:"txnType" binding:"required,oneof=auth void refund"`
		MCC                 string  `json:"mcc" binding:"required"`
		MerchantName        string  `json:"merchantName" binding:"required"`
		MerchantCountry     string  `json:"merchantCountry" binding:"required"`
		MerchantCity        string  `json:"merchantCity" binding:"required"`
		MerchantPostcode    string  `json:"merchantPostcode" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证交易类型
	if req.TxnType == "void" || req.TxnType == "refund" {
		if req.OriginTransactionID == "" {
			common.Error(ctx, http.StatusBadRequest, "origin_transaction_id_required", nil)
			return
		}
	}

	bodyBytes, err := json.Marshal(req)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "json_format_error", err)
		return
	}

	result, err := services.SimulateTransaction(ctx.Request.Context(), c.client, bodyBytes)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "simulate_transaction_failed", err)
		return
	}

	ctx.Data(http.StatusOK, "application/json", result)
}
